package pers.kw.job.server.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.kw.dozer.BeanMapper;
import pers.kw.entity.PageDto;
import pers.kw.exceptions.job.TaskException;
import pers.kw.job.server.constant.ScheduleConstants;
import pers.kw.job.server.dto.mgr.QueryJobReqDto;
import pers.kw.job.server.dto.mgr.SysJobDto;
import pers.kw.job.server.persist.dao.SysJobDao;
import pers.kw.job.server.persist.entity.SysJobDO;
import pers.kw.job.server.persist.mapper.SysJobMapper;
import pers.kw.job.server.util.CronUtils;
import pers.kw.job.server.util.ScheduleUtils;
import pers.kw.utils.DoWrapUtil;
import pers.kw.utils.SnowFlake;
import pers.kw.utils.poi.ExcelUtil;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 定时任务调度信息 服务层
 *
 * @author ruoyi
 */
@Slf4j
@Service
public class SysJobService {
    @Resource
    private Scheduler scheduler;

    @Resource
    private SysJobMapper jobMapper;

    @Resource
    private BeanMapper beanMapper;

    @Resource
    private SysJobDao sysJobDao;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJobDO> jobList = jobMapper.selectJobAll();
        for (SysJobDO job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    public void export(HttpServletResponse response, QueryJobReqDto sysJob) {
        List<SysJobDto> list = jobMapper.selectJobList(sysJob);
        ExcelUtil<SysJobDto> util = new ExcelUtil<>(SysJobDto.class);
        util.exportExcel(response, list, "定时任务");
    }


    /**
     * 获取quartz调度器的计划任务列表
     *
     * @param reqDto 调度信息
     * @return
     */
    public PageDto<SysJobDto> pageQueryJobList(QueryJobReqDto reqDto) {
        log.info("分页查询job列表，入参:{}", JSON.toJSONString(reqDto));
        Page<SysJobDto> selectResult = PageHelper.startPage(reqDto.getPageNum(), reqDto.getPageSize());
        jobMapper.selectJobList(reqDto);
        PageDto<SysJobDto> page = DoWrapUtil.page(selectResult);
        log.info("分页查询job列表，出参:{}", JSON.toJSONString(page));
        //PageHelper.clearPage();
        return page;
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param bizCode 调度任务ID
     * @return 调度任务对象信息
     */
    public SysJobDto selectJobById(String bizCode) {
        return beanMapper.convert(sysJobDao.findByBizCode(bizCode), SysJobDto.class);
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJobDO job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJobDO job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJobDO job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = jobMapper.deleteJobById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     *
     * @param jobBizCodes 需要删除的任务ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByBizCode(String[] jobBizCodes) throws SchedulerException {
        for (String jobBizCode : jobBizCodes) {
            SysJobDO sysJobDO = sysJobDao.findByBizCode(jobBizCode);
            if (sysJobDO != null && sysJobDO.getJobId() != null) {
                deleteJob(sysJobDO);
            }
        }
    }

    /**
     * 任务调度状态修改
     *
     * @param reqDto 调度信息请求参数
     */
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJobDto reqDto) throws SchedulerException {
        int rows = 0;
        String status = reqDto.getStatus();
        //查询job
        SysJobDO job = sysJobDao.findByBizCode(reqDto.getBizCode());
        //跟新调度状态
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJobDto job) throws SchedulerException {
        boolean result = false;
        SysJobDO properties = sysJobDao.findByBizCode(job.getBizCode());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(properties.getJobId(), properties.getJobGroup());
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     *
     * @param reqDto 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertJob(SysJobDto reqDto) throws SchedulerException, TaskException {
        SysJobDO job = new SysJobDO();
        job.setBizCode(SnowFlake.getSnowId());
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        job.setRemark(reqDto.getRemark());
        job.setJobName(reqDto.getJobName());
        job.setJobGroup(reqDto.getJobGroup());
        job.setInvokeTarget(reqDto.getInvokeTarget());
        job.setCronExpression(reqDto.getCronExpression());
        job.setMisfirePolicy(reqDto.getMisfirePolicy());
        job.setConcurrent(reqDto.getConcurrent());
        job.setStatus(reqDto.getStatus());
        job = sysJobDao.save(job);
        if (job.getJobId() != null) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 更新任务的时间表达式
     *
     * @param reqDto 调度信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJob(SysJobDto reqDto) throws SchedulerException, TaskException {
        SysJobDO job = sysJobDao.findByBizCode(reqDto.getBizCode());
        String jobGroup = job.getJobGroup();
        job.setRemark(reqDto.getRemark());
        job.setJobName(reqDto.getJobName());
        job.setJobGroup(reqDto.getJobGroup());
        job.setInvokeTarget(reqDto.getInvokeTarget());
        job.setCronExpression(reqDto.getCronExpression());
        job.setMisfirePolicy(reqDto.getMisfirePolicy());
        job.setConcurrent(reqDto.getConcurrent());
        job.setStatus(reqDto.getStatus());
        DoWrapUtil.update(job, false);
        sysJobDao.save(job);
        updateSchedulerJob(job, jobGroup);
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJobDO job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }
}